<?php


namespace app\traits;

use think\exception\HttpResponseException;
use think\response\Json;

trait Response
{
	public function writeJson($code = 1, $msg = '', $data = "", $type = 'json', array $header = []): Json
	{
		if (!is_int($code)) {
			$result = [
				'code' => 1,
				'msg' => $msg,
				'data' => $code
			];
		} else {
			$result = [
				'code' => $code,
				'msg' => $msg,
				'data' => $data
			];
		}
		// 如果未设置类型则自动判断
		if (isset($header['statuscode'])) {
			$code = $header['statuscode'];
			unset($header['statuscode']);
		} else {
			//未设置状态码,根据code值判断
			$code = $result['code'] >= 401 || $result['code'] < 200 ? 200 : $result['code'];
		}
		$response = \think\Response::create($result, $type, $code)->header($header);
		throw new HttpResponseException($response);
	}
}